#电量计算器
import datetime
import math


class TCalculator:
    def __init__(self):
        self.settings = {}
        self.tdb = None
        self.tdbCode =""
    def getLiYangPowerStatic(self , staticDatetime):
        res ={
            "status":0,
            "staticTime":{
                "local": staticDatetime.strftime("%Y-%m-%d %H:%M:%S") ,
                "utc": (staticDatetime - datetime.timedelta(hours=8)).strftime("%Y-%m-%dT%H:%M:%SZ")
            },
            "keys":[
                "1113","1114","1115","1116","1118","1119","1157"
            ],
            "datas": {
                "year":{
                    "from":"",
                    "to":"",
                    "sql":"",
                    "detail":{},
                    "static":{}
                },
                "month":{
                    "from":"",
                    "to":"",
                    "sql":"",
                    "detail":{},
                    "static":{}
                },
                "day":{
                    "from":"",
                    "to":"",
                    "sql":"",
                    "detail":{},
                    "static":{}
                },
                "hour":{
                    "from":"",
                    "to":"",
                    "sql":"",
                    "detail":{},
                    "static":{}
                }
            },
            "static":{}
        }
        try:
            tmUtc = staticDatetime - datetime.timedelta(hours=8)
            # year
            fromTm = datetime.datetime( staticDatetime.year , 1,1 ) - datetime.timedelta(hours=8)
            toTm = datetime.datetime( staticDatetime.year + 1 , 1,1 ) - datetime.timedelta(hours=8)
            if tmUtc < toTm :
                toTm = tmUtc
            res['datas']['year']['from'] = fromTm.strftime('%Y-%m-%dT%H:%M:%SZ')
            res['datas']['year']['to'] = toTm.strftime('%Y-%m-%dT%H:%M:%SZ')
            # month
            fromTm = datetime.datetime( staticDatetime.year , staticDatetime.month , 1 ) - datetime.timedelta(hours=8)
            endYear = staticDatetime.year + 1 if staticDatetime.month == 12 else staticDatetime.year
            endMonth = staticDatetime.month + 1 if staticDatetime.month<12 else 1
            toTm = datetime.datetime( endYear , endMonth , 1 ) - datetime.timedelta( hours=8 )
            if tmUtc < toTm :
                toTm = tmUtc
            res['datas']['month']['from'] = fromTm.strftime('%Y-%m-%dT%H:%M:%SZ')
            res['datas']['month']['to'] = toTm.strftime('%Y-%m-%dT%H:%M:%SZ')
            # day
            fromTm = datetime.datetime( staticDatetime.year , staticDatetime.month , staticDatetime.day) - datetime.timedelta( hours=8 )
            toTm = tmUtc
            res['datas']['day']['from'] = fromTm.strftime('%Y-%m-%dT%H:%M:%SZ')
            res['datas']['day']['to'] = toTm.strftime('%Y-%m-%dT%H:%M:%SZ')
            # hour
            fromTm = datetime.datetime( staticDatetime.year , staticDatetime.month , staticDatetime.day , staticDatetime.hour) - datetime.timedelta( hours=9 )
            toTm = tmUtc
            res['datas']['hour']['from'] = fromTm.strftime('%Y-%m-%dT%H:%M:%SZ')
            res['datas']['hour']['to'] = toTm.strftime('%Y-%m-%dT%H:%M:%SZ')
            # generate sql , query
            keys = " or ".join([ 'varId=\'' + str(k) +'\'' for k in res['keys']])
            sqlFormat = " select  first(v) as v0, last(v) as v1,  spread(v) as diff  from varZniot2024 where ("+keys+") and time  >='fromDt'  and time  <='endDt'  group by varId  order by time limit 10000 tz('Asia/Shanghai')"
            for itemKey in res['datas'].keys():
                item = res['datas'][itemKey]
                for k in res['keys']:
                    item['detail'][str(k)+'_v0'] = 0
                    item['detail'][str(k)+'_v1'] = 0
                    item['detail'][str(k)+'_diff'] = 0
                sql = sqlFormat.replace('fromDt' , item['from']).replace('endDt' , item['to'])
                item['sql'] = sql
                queryResult = self.tdb.query(self.tdbCode , sql)
                flag = ( 'result' in queryResult.keys() ) and (len(queryResult['result'])>0) and ('series' in queryResult['result'][0].keys())
                if flag :
                    datas = queryResult['result'][0]['series']
                    for row  in datas:
                        varId = row['tags']['varId']
                        for i in range(len(row['columns'])):
                            if i >0 :
                                c = row['columns'][i]
                                v = row['values'][0][i]
                                k = str(varId) + '_' + c
                                item['detail'][k] = v
            # static
            for itemKey in res['datas'].keys():
                item = res['datas'][itemKey]
                detail = item['detail']
                downNetPower = detail['1118_diff']
                upNetPower = detail['1119_diff']
                generatePower = detail['1113_diff'] + detail['1114_diff'] + detail['1115_diff'] + detail['1116_diff']
                usedPower = downNetPower + generatePower - upNetPower
                unPower = detail['1157_diff']
                totalPf = 0
                if math.sqrt(downNetPower * downNetPower + unPower * unPower)>0 :
                    totalPf = downNetPower / math.sqrt(downNetPower * downNetPower + unPower * unPower)
                item['static'] ={
                    "down": downNetPower ,
                    "up": upNetPower ,
                    "generate": generatePower ,
                    "used" :usedPower ,
                    "unPower": unPower ,
                    "totalPf" : round( totalPf,2 )
                }
            '''
                for sk in item['static'].keys():
                    res['static'][itemKey+'_'+sk] = item[sk]
            '''
            for itemKey in res['datas'].keys():
                item = res['datas'][itemKey]
                res['static'][itemKey] = item['static']
            res['status'] = 1
        except Exception as er:
            print(er)
        return  res
    def getLiyangPowersBJ(self , y , m , d , h ):
        res ={}
        try:
            dt = datetime.datetime( y , m ,d , h , 0 , 0 )
            res = self.getLiYangPowerStatic(dt)
        except Exception as er :
            print(er)
        return  res

